package com.seres.gate.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Tan-Bowen
 * @version 1.0
 * @description TODO
 * @date 2021/8/16 19:00
 */
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)//控制过滤器的级别最高
public class CorsFilter extends ZuulFilter {

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 2;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext context = RequestContext.getCurrentContext();
        HttpServletRequest reqs = context.getRequest();
        context.addZuulResponseHeader("Access-Control-Allow-Origin", reqs.getHeader("Origin"));
        context.addZuulResponseHeader("Access-Control-Allow-Credentials", "true");
        context.addZuulResponseHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
        context.addZuulResponseHeader("Access-Control-Allow-Headers", "Authorization, Content-Type,X-Requested-With");
        context.addZuulResponseHeader("Access-Control-Max-Age", "3600");
        return null;
    }
}
